import 'package:flutter/material.dart';
import 'package:flutter_local/base/BaseItemPage.dart';
import 'package:flutter_local/entity/MethodParams.dart';
import 'package:flutter_local/ext/Any.dart';
import 'package:flutter_local/opt/DataPacker.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:walletconnect_dart/walletconnect_dart.dart';

class WalletPage extends BaseItemPage {

  final sessionLs = <WalletConnect>[];

  final connectAccounts = <String>[];

  Uri? deepLinkUri;

  @override
  List<Widget> getItems() {
    return <Widget>[
      addItemWidget("创建Session", () {
        createSession();
      }),
      addItemWidget("关闭Session", () {
        killSession();
      }),
      addItemWidget("Deeplink", () {
        deepLink(deepLinkUri);
      }),
      addItemWidget("signedTypedV4", () {
        scheduleMethod(packSignTypedMethod(getConnectAddress() ?? ""));
      }),
      addItemWidget("signedTransaction", () {

      }),
      addItemWidget("signPersonalMessage", () {
        scheduleMethod(
            packSignPersonalMethod("我是你爹", getConnectAddress() ?? ""));
      }),
    ];
  }

  Future<void> createSession() async {
    if (sessionLs.isEmpty) {
      final connector = WalletConnect(
          bridge: "https://bridge.walletconnect.org",
          clientMeta: const PeerMeta(
              url: "https://www.baidu.com",
              description: "百度",
              name: "lemonApp",
              icons: ["https://www.dapp.com/img/Icon_Logotype_2.png"]));
      connector.on("connect", (event) {
        var acc = (event as SessionStatus?)?.accounts;
        print("已连接 $acc");
        if (acc?.isNotEmpty == true) {
          connectAccounts.addAll(acc!);
        }
      });
      connector.on('disconnect', (session) {
        //如果链接断开 那么清除当前session 重新创建
        print("链接断开$session");
        killSession();
      });
      connector.on(
          "session_request", (event) => print("Session request $event"));
      connector.on("session_update", (event) => print("Session update $event"));
      sessionLs.add(connector);
      if (!connector.connected) {
        final session = await connector.createSession(
            chainId: 80001,
            onDisplayUri: (uri) {
              print("Session已创建，等待deepLink=>$uri");
              deepLinkUri = Uri.parse(uri);
            });
      }
    } else {
      print("Session已创建，当前连接:${sessionLs.firstOrNull()?.session.accounts}");
    }
  }

  Future<void> deepLink(Uri? uri) async {
    if (uri == null) {
      print("uri为null，请先创建session");
      return;
    }
    var r = await canLaunchUrl(uri);
    if (r) {
      var r2 = await launchUrl(uri);
      print("跳转结果:$uri=>$r2");
    } else {
      throw 'Could not launch $uri';
    }
  }

  Future<void> killSession() async {
    if (sessionLs.isEmpty) {
      print("Session为空");
    } else {
      await sessionLs.firstOrNull()?.killSession();
      sessionLs.removeAt(0);
      connectAccounts.clear();
      print("session已kill，connectAccounts已清空");
    }
  }

  bool checkConnect() {
    if (isConnected()) {
      print("当前已连接到${getConnectAddress()}");
      return true;
    } else {
      print("当前还未连接");
      return false;
    }
  }

  bool isConnected() {
    return deepLinkUri != null && getConnectAddress() != null;
  }

  String? getConnectAddress() {
    return connectAccounts.firstOrNull();
  }

  /// 执行eth函数
  Future<void> scheduleMethod(EthMethod method, {bool jump = true}) async {
    if (!checkConnect()) return;
    if (jump && deepLinkUri != null) {//${deepLinkUri?.path}不要这个是一样的效果
      final dumpUri = "${deepLinkUri?.scheme}:";
      deepLink(Uri.parse(dumpUri));
    }
    final connect = sessionLs.firstOrNull();
    try {
      dynamic result = await connect?.sendCustomRequest(
          method: method.name, params: method.packData());
      if (result is String) {
        print("签名结果:$result");
      } else {
        print("未知结果:$result");
      }
    } catch (e) {
      print("异常:$e");
    }
  }
}
